import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AddEmployeePage(
        title: '新增员工',
      ),
    );
  }
}

// ----数据添加页面--------------------------
class AddEmployeePage extends StatefulWidget {
  final String title;

  AddEmployeePage({Key key, this.title}) : super(key: key);

  @override
  _AddEmployeePageState createState() => _AddEmployeePageState();
}

class _AddEmployeePageState extends State<AddEmployeePage> {
  Employee employee = new Employee('', '', '', '');
  String firstName;
  String lastName;
  String mobileNo;
  String email;
  final scaffoldKey = new GlobalKey<ScaffoldState>();
  final formKey = new GlobalKey<FormState>();

  void _submit() {
    if (this.formKey.currentState.validate()) {
      formKey.currentState.save();
    } else {
      return null;
    }

    var employee = Employee(firstName, lastName, mobileNo, email);
    var dbHelper = DBHelper();
    dbHelper.saveEmployee(employee);
    this.formKey.currentState.reset();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        title: Text('新增员工'),
        actions: [
          IconButton(
              icon: const Icon(Icons.view_list),
              onPressed: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => EmployeeListPage()));
              })
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: formKey,
          child: Column(
            children: [
              TextFormField(
                keyboardType: TextInputType.text,
                decoration: InputDecoration(labelText: '姓氏'),
                validator: (val) => val.length == 0 ? '请输入姓氏' : null,
                onSaved: (val) => this.firstName = val,
              ),
              TextFormField(
                keyboardType: TextInputType.text,
                decoration: InputDecoration(labelText: '名字'),
                validator: (val) => val.length == 0 ? '请输入名字' : null,
                onSaved: (val) => this.lastName = val,
              ),
              TextFormField(
                keyboardType: TextInputType.text,
                decoration: InputDecoration(labelText: '电话'),
                validator: (val) => val.length == 0 ? '请输入电话' : null,
                onSaved: (val) => this.mobileNo = val,
              ),
              TextFormField(
                keyboardType: TextInputType.text,
                decoration: InputDecoration(labelText: '邮箱'),
                validator: (val) => val.length == 0 ? '请输入邮箱' : null,
                onSaved: (val) => this.email = val,
              ),
              Container(
                margin: const EdgeInsets.only(top: 10.0),
                child: RaisedButton(
                  child: Text('保存'),
                  onPressed: _submit,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

// ----数据列表页面--------------------------
Future<List<Employee>> fetchEmployeeFromDB() async {
  var db = DBHelper();
  return db.getEmployees();
}

class EmployeeListPage extends StatefulWidget {
  @override
  _EmployeeListPageState createState() => _EmployeeListPageState();
}

class _EmployeeListPageState extends State<EmployeeListPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('员工列表'),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: FutureBuilder<List<Employee>>(
          future: fetchEmployeeFromDB(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemBuilder: (context, index) {
                  Employee employee = snapshot.data[index];
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        employee.firstName,
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18.0),
                      ),
                      Text(employee.lastName),
                      Text(employee.mobileNo),
                      Text(employee.email),
                      Divider(),
                    ],
                  );
                },
                itemCount: snapshot.data.length,
              );
            } else if (snapshot.hasError) {
              return Text('查询失败:${snapshot.error}');
            }
            return Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            );
          },
        ),
      ),
    );
  }
}

// ----数据库工具类--------------------------
class DBHelper {
  static Database _db;

  // 初始化数据库
  void _onCreate(Database db, int version) async {
    await db
        .execute('CREATE TABLE Employee (id INTEGER PRIMARY KEY,firstname TEXT'
            ',lastname TEXT,mobileno TEXT,email TEXT)');
  }

  // 在本地文件创建数据库文件
  initDB() async {
    String dirPath = (await getApplicationDocumentsDirectory()).path;
    String path = join(dirPath, 'data.db');
    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }

  // 获取数据库
  Future<Database> get db async {
    if (_db != null) return _db;
    _db = await initDB();
    return _db;
  }

  // 保存数据
  void saveEmployee(Employee employee) async {
    var dbClient = await db;
    String sql = 'INSERT INTO Employee (firstname,lastname,mobileno,email) '
        'VALUES ("${employee.firstName}","${employee.lastName}",'
        '"${employee.mobileNo}","${employee.email}")';
    // ${employee.firstName},${employee.lastName},${employee.mobileNo},${employee.email}
    await dbClient.transaction((txn) async {
      return await txn.rawInsert(sql);
    });
  }

  // 查询全部数据
  Future<List<Employee>> getEmployees() async {
    var dbClient = await db;
    List<Map> list = await dbClient.rawQuery('SELECT * FROM Employee');
    List<Employee> employeeList = List();
    for (var value in list) {
      employeeList.add(Employee(value['firstname'], value['lastname'],
          value['mobileno'], value['email']));
    }
    return employeeList;
  }
}

// -----实体model--------------------------
class Employee {
  String firstName;
  String lastName;
  String mobileNo;
  String email;

  Employee(this.firstName, this.lastName, this.mobileNo, this.email);

  Employee.fromMap(Map map) {
    firstName = map[firstName];
    lastName = map[lastName];
    mobileNo = map[mobileNo];
    email = map[email];
  }
}
